package com.javaex.book.utils;

import java.io.File;
import java.util.Arrays;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传工具类
 *
 * @author 黄星琦
 * @Date 2022年3月9日
 */
public class UploadUtils {
	
	private static final Logger logger = LoggerFactory.getLogger(UploadUtils.class);

	/** 上传文件存放路径 */
	public static final String UPLOAD_DIR = "/upload";
	/** 上传图片类型 */
	public static final String[] UPLOAD_IMAGE_TYPE = new String[] { "png", "jpg", "jpeg", "gif", "webp", "svg" };
	public static final Integer UPLOAD_IMAGE_MAX_SIZE = 5000000;
	
	public static ReturnResult uploadImage(MultipartFile uploadImage, HttpServletRequest req) {
		// 判断上传文件是否为空
		if (uploadImage == null || uploadImage.isEmpty()) {
			 return ReturnResult.fail("上传文件为空");
		}
		// 判断文件大小
		if (uploadImage.getSize() > UPLOAD_IMAGE_MAX_SIZE) {
			return ReturnResult.fail("文件太大，上传失败");
		}
		// 获取文件后缀名
		String extension = FilenameUtils.getExtension(uploadImage.getOriginalFilename());
		// 判断文件类型
		if (!Arrays.asList(UPLOAD_IMAGE_TYPE).contains(extension)) {
			return ReturnResult.fail("上传文件类型不支持");
		}
		// 新文件名
		String fileName = UUID.randomUUID().toString().replace("-", "") + "." + extension;
		// 文件输出路径
		String outPath = req.getServletContext().getRealPath(UPLOAD_DIR) + File.separator + fileName;
		File file = new File(outPath);
		try {
			// 写入图片
			uploadImage.transferTo(file);
			logger.info("上传图片：{}", outPath);
		} catch (Exception e) {
			logger.error("文件上传失败", e);
			return ReturnResult.fail("文件上传失败");
		} 
		// 返回文件位置
		return ReturnResult.success("上传成功", UPLOAD_DIR + "/" + fileName);
	}
}
